<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.9.2" />
<title>ascend.data API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<link rel="preconnect" href="https://www.google.com">
<script async src="https://cse.google.com/cse.js?cx=017837193012385208679:pey8ky8gdqw"></script>
<style>
.gsc-control-cse {padding:0 !important;margin-top:1em}
body.gsc-overflow-hidden #sidebar {overflow: visible;}
</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
<style>.homelink{display:block;font-size:2em;font-weight:bold;color:#555;padding-bottom:.5em;border-bottom:1px solid silver}.homelink:hover{color:inherit}.homelink img{max-width:20%;max-height:5em;margin:auto;margin-bottom:.3em}</style>
<link rel="canonical" href="https://bazige.github.io/ascend/data/">
<link rel="icon" href="https://bazige.github.io/ascend/logo/logo.png"">
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>ascend.data</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/__init__.py#L0-L5" class="git-link">Browse git</a>
</summary>
<pre><code class="python">from .ascendarray import AscendArray
from .tensor import imgs2tensor, tensor2imgs

__all__ = [
    &#39;AscendArray&#39;, &#39;imgs2tensor&#39;, &#39;tensor2imgs&#39;,
]</code></pre>
</details>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="ascend.data.ascendarray" href="ascendarray.html">ascend.data.ascendarray</a></code></dt>
<dd>
<div class="desc"><p>Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in …</p></div>
</dd>
<dt><code class="name"><a title="ascend.data.tensor" href="tensor.html">ascend.data.tensor</a></code></dt>
<dd>
<div class="desc"><p>Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in …</p></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="ascend.data.imgs2tensor"><code class="name flex">
<span>def <span class="ident">imgs2tensor</span></span>(<span>imgs, tensor_fmt='NCHW', tensor_ptr=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert 3-channel images to tensor</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>imgs</code></strong> :&ensp;<code>list[<a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a>]</code></dt>
<dd>A list that contains multiple images,
shape (h, w, c), support RGB/BGR, YUV444</dd>
<dt><strong><code>tensor_fmt</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Data format of output tensor. Defaults to 'NCHW'.</dd>
<dt><strong><code>tensor_ptr</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Data pointer of output tensor. If it is None,
we will create an AscendArray and bind the array's data pointer to it.
Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a></code></dt>
<dd>Tensor that contains multiple images, shape (N, C, H, W)
or shape (N, H, W, C)</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">imgs = [ascend_array1, ascend_array2]
data = ascend.imgs2tensor(imgs, tensor_fmt='NHWC')
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/tensor.py#L38-L106" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imgs2tensor(imgs, tensor_fmt=&#39;NCHW&#39;, tensor_ptr=None):
    &#34;&#34;&#34;Convert 3-channel images to tensor

    Args:
        imgs (list[AscendArray]): A list that contains multiple images,
            shape (h, w, c), support RGB/BGR, YUV444
        tensor_fmt (str, optional): Data format of output tensor. Defaults to &#39;NCHW&#39;.
        tensor_ptr (int, optional): Data pointer of output tensor. If it is None, 
            we will create an AscendArray and bind the array&#39;s data pointer to it. 
            Defaults to None.

    Returns:
        AscendArray: Tensor that contains multiple images, shape (N, C, H, W) 
            or shape (N, H, W, C)

    Typical usage example:
    ```python
    imgs = [ascend_array1, ascend_array2]
    data = ascend.imgs2tensor(imgs, tensor_fmt=&#39;NHWC&#39;)
    ```
    &#34;&#34;&#34;
    if not isinstance(imgs, list):
        raise TypeError(f&#34;Input imgs expects a list, but got {type(imgs)}.&#34;)

    if len(imgs) &lt;= 0:
        raise ValueError(f&#34;Input imgs is a null list.&#34;)

    # get first image&#39;s shape and format
    format = imgs[0].format
    _shape = imgs[0].shape
    if format in yuv420:
        shape = _shape + (1,)
    else:
        shape = _shape

    # generate output tensor shape
    if tensor_fmt == &#39;NCHW&#39;:
        tensor_shape = (len(imgs),) + shape[-1:] + shape[:-1]
    elif tensor_fmt == &#39;NHWC&#39;:
        tensor_shape = (len(imgs),) + shape
    else:
        raise ValueError(
            f&#34;Tensor format only accept &#39;NCHW&#39; or &#39;NHWC&#39;, but got {tensor_fmt}.&#34;)

    if not tensor_ptr:
        tensor = AscendArray(
            tensor_shape, dtype=imgs[0].dtype, format=tensor_fmt)
        _ptr = tensor.ascend_data
    else:
        assert isinstance(tensor_ptr, int), \
            f&#34;Input tensor_ptr expects an int, but got {type(tensor_ptr)}.&#34;
        _ptr = tensor_ptr

    nbytes = 0
    for i, img in enumerate(imgs):
        assert _shape == img.shape, f&#34;imgs[{i}]&#39;s shape {img.shape} is not same to others.&#34;
        assert format == img.format, f&#34;imgs[{i}]&#39;s format {img.shape} is not same to others.&#34;

        if tensor_fmt == &#39;NCHW&#39;:
            # swap channel using transform operator
            &#39;&#39;&#39;
            to do transformer
            &#39;&#39;&#39;
            pass

        nbytes = nbytes + img.nbytes
        memcpy_d2d(_ptr + nbytes, img.ascend_data, img.nbytes)

    return tensor if not tensor_ptr else None</code></pre>
</details>
</dd>
<dt id="ascend.data.tensor2imgs"><code class="name flex">
<span>def <span class="ident">tensor2imgs</span></span>(<span>tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert tensor to a 3-channel images</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>tensor</code></strong> :&ensp;<code><a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a></code></dt>
<dd>Tensor that contains multiple images, shape (N, C, H, W) or shape (N, H, W, C)</dd>
<dt><strong><code>mean</code></strong> :&ensp;<code>tuple[float]</code>, optional</dt>
<dd>The mean value of images. Defaults to (0, 0, 0).</dd>
<dt><strong><code>std</code></strong> :&ensp;<code>tuple[float]</code>, optional</dt>
<dd>The standard deviation of images. Defaults to (1, 1, 1).</dd>
<dt><strong><code>to_rgb</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Whether the tensor was converted to RGB format in the first place.
If so, convert it back to BGR. Defaults to True.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list[np.ndarray]</code></dt>
<dd>A list that contains multiple images.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">imgs = ascend.tensor2imgs(tensors)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/tensor.py#L109-L161" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True):
    &#34;&#34;&#34;Convert tensor to a 3-channel images

    Args:
        tensor (AscendArray): Tensor that contains multiple images, shape (N, C, H, W) or shape (N, H, W, C)
        mean (tuple[float], optional): The mean value of images. Defaults to (0, 0, 0).
        std (tuple[float], optional): The standard deviation of images. Defaults to (1, 1, 1).
        to_rgb (bool, optional): Whether the tensor was converted to RGB format in the first place.
            If so, convert it back to BGR. Defaults to True.

    Returns:
        list[np.ndarray]: A list that contains multiple images.

    Typical usage example:
    ```python
    imgs = ascend.tensor2imgs(tensors)
    ```
    &#34;&#34;&#34;
    if not isinstance(tensor, AscendArray):
        raise TypeError(
            f&#34;Input tensor expects an AscendArray, but got {type(tensor)}.&#34;)

    if tensor.ndim != 4:
        raise ValueError(
            f&#34;Input tensor expects a 4-dim, but got {tensor.ndim}.&#34;)

    if tensor.format not in [&#34;NCHW&#34;, &#34;NHWC&#34;]:
        raise ValueError(
            f&#34;Input tensor&#39;s format only support &#39;NCHW&#39; or &#39;NHWC&#39;, but given {tensor.format}.&#34;)

    assert len(mean) == 3, \
        f&#34;Input mean of images expects a 3-elements tuple, but got {len(mean)}.&#34;
    assert len(std) == 3, \
        f&#34;Input std of images expects a 3-elements tuple, but got {len(std)}.&#34;

    batch_size = tensor.shape[0]
    mean = np.array(mean, dtype=np.float32)
    std = np.array(std, dtype=np.float32)

    if tensor.format == &#34;NCHW&#34;:
        try:
            tensor = Permute(tensor, axes=(0, 2, 3, 1))
        except:
            tensor = tensor.to_np.transpose(0, 2, 3, 1)
    else:
        tensor = tensor.to_np

    imgs = []
    for img_id in range(batch_size):
        img = tensor[img_id, ...]
        img = _imdenormalize(img, mean, std, to_bgr=to_rgb).astype(np.uint8)
        imgs.append(np.ascontiguousarray(img))
    return imgs</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="ascend.data.AscendArray"><code class="flex name class">
<span>class <span class="ident">AscendArray</span></span>
<span>(</span><span>shape, dtype, size=0, buffer=None, format=None, context=None, flag='DEVICE')</span>
</code></dt>
<dd>
<div class="desc"><p>Define a AscendArray data class like numpy ndarray.</p>
<pre><code>class private attributes:
_nbytes (int)    : the bytes of AscendArray's data
_shape (tuple)   : the shape of this array
_dtype (int)     : the acl data type of AscendArray
_flag (int)      : the flag of defined memory malloc on device/host/dvpp
_mem (instance)  : save the instance of class Memory()
_data (a pointer): the mem ptr of AscendArray's data
</code></pre>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>ascend_data</code></strong> :&ensp;<code>int</code></dt>
<dd>Get(read) the pointer of data malloced by itself(_data's value),
or band it to a new memory.</dd>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple</code></dt>
<dd>Tuple of array dimensions. (should work with write ascend_data).</dd>
<dt><strong><code>ndim</code></strong> :&ensp;<code>int</code></dt>
<dd>Number of array dimensions.</dd>
<dt><strong><code>dtype</code></strong> :&ensp;<code>np.dtype</code></dt>
<dd>get or write the data type.</dd>
<dt><strong><code>size</code></strong> :&ensp;<code>int</code></dt>
<dd>Number of elements in the array.</dd>
<dt><strong><code>nbytes</code></strong> :&ensp;<code>int</code></dt>
<dd>Total bytes consumed by the elements of the array.</dd>
<dt><strong><code>itemsize</code></strong> :&ensp;<code>int</code></dt>
<dd>Length of one AscendArray element in bytes, which equal to size * dtype(size).</dd>
<dt><strong><code>flag</code></strong> :&ensp;<code>str</code></dt>
<dd>Information about the memory layout of the array.</dd>
</dl>
<div class="admonition hint">
<p class="admonition-title">Hint</p>
<ul>
<li>reshape
: Gives a new shape to an array without changing its data.</li>
<li>resize
: Return a new array with the specified shape.</li>
<li>to_np
: Use this function to copy device data to host and formal like numpy array.</li>
<li>to_ascend : trans a ndarray data to AscendArray(i.e. feed this instance with a numpy array data).</li>
<li>clone
: new a AscendArray object clone from np.ndarray</li>
<li>to
: copy this instance's data to another same shape AscendArray.</li>
<li>astype
: Copy of the array, cast to a specified type.</li>
<li>transpose : Reverse or permute the axes of an array; returns the modified array.</li>
</ul>
</div></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L21-L567" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class AscendArray():
    &#34;&#34;&#34;Define a AscendArray data class like numpy ndarray.

        class private attributes:
        _nbytes (int)    : the bytes of AscendArray&#39;s data
        _shape (tuple)   : the shape of this array
        _dtype (int)     : the acl data type of AscendArray
        _flag (int)      : the flag of defined memory malloc on device/host/dvpp
        _mem (instance)  : save the instance of class Memory()
        _data (a pointer): the mem ptr of AscendArray&#39;s data

    Attributes:
        ascend_data (int): Get(read) the pointer of data malloced by itself(_data&#39;s value), 
            or band it to a new memory.
        shape (tuple): Tuple of array dimensions. (should work with write ascend_data).
        ndim (int): Number of array dimensions.
        dtype (np.dtype): get or write the data type.
        size (int): Number of elements in the array.
        nbytes (int): Total bytes consumed by the elements of the array.
        itemsize (int): Length of one AscendArray element in bytes, which equal to size * dtype(size).
        flag (str): Information about the memory layout of the array.

    .. hint:: 
        - reshape   : Gives a new shape to an array without changing its data.
        - resize    : Return a new array with the specified shape.
        - to_np     : Use this function to copy device data to host and formal like numpy array.
        - to_ascend : trans a ndarray data to AscendArray(i.e. feed this instance with a numpy array data).
        - clone     : new a AscendArray object clone from np.ndarray
        - to        : copy this instance&#39;s data to another same shape AscendArray.
        - astype    : Copy of the array, cast to a specified type.
        - transpose : Reverse or permute the axes of an array; returns the modified array.
    &#34;&#34;&#34;

    def __init__(self, shape, dtype, size=0, buffer=None, format=None, context=None, flag=&#39;DEVICE&#39;):
        assert isinstance(shape, tuple), \
            f&#39;Input shape of AscendArray instance expects tuple, but got {type(shape)}&#39;

        try:
            self._dtype = np.dtype(dtype)
        except:
            raise TypeError(
                f&#39;Input dtype expect a numpy.dtype, but got {type(dtype)}&#39;)

        self._shape = shape
        self._flag = flag
        self._context = context
        self._format = format

        bind_context(context)

        is_malloc = True
        # calc memory size according to variable calling
        # 1. initial a scalar
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((), dtype=np.int32)
        if shape == ():
            self._nbytes = self._dtype.itemsize

        # 2. initial a array with shape(2, 3):
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((2, 3), dtype=np.float16)
        elif size &lt;= 0 and buffer is None:
            self._nbytes = int(np.prod(shape) * self._dtype.itemsize)

        # 3. initial a array with shape(6,) and 256 bytes
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((6,), dtype=np.float32, size=256)
        elif buffer is None:
            self._nbytes = size
            self._shape = (shape[0], size//(shape[0] * self._dtype.itemsize))

        # 4. initial a array with shape(16,) and binding memory pointer mem_ptr
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((16,), dtype=np.float16, size=256, buffer=mem_ptr)
        else:
            self._nbytes = size
            self._shape = (shape[0], size//(shape[0] * self._dtype.itemsize))
            is_malloc = False

        # bind memory
        if is_malloc:
            self._mem = Memory(self._context, self._nbytes, flag)
            self._data = self._mem.ptr
        else:
            self._data = buffer

    # 1.ascend_data getter and setter
    @property
    def ascend_data(self): 
        return self._data

    @ascend_data.setter
    def ascend_data(self, dev_ptr: int):
        assert isinstance(dev_ptr, int), \
            f&#39;Function dev_ptr args of input expects int type, but got {type(dev_ptr)}&#39;

        if hasattr(self, &#39;_mem&#39;):
            del self._mem
        self._data = dev_ptr

    # 2.memory location getter
    @property
    def flag(self):
        return self._flag

    # 3.context resource getter and setter
    @property
    def context(self):
        return self._context

    @context.setter
    def context(self, context):
        &#34;&#34;&#34;Binding AscendArray with a new context.

        .. warning::
            Only support the memory of AscendArray create by itself.

        Args:
            context : the context to be binded.

        Returns:
            None.
        &#34;&#34;&#34;
        assert isinstance(context, int), \
            f&#34;Input context expects int value, but got {type(context)}.&#34;

        if not hasattr(self, &#39;_mem&#39;):
            raise ValueError(
                f&#34;This AscendArray instance not support to set context.&#34;)
        else:
            del self._mem

        bind_context(context)
        self._mem = Memory(context, self._nbytes, self._flag)
        self._data = self._mem.ptr

    # 4.ndim getter
    @property
    def ndim(self):
        return len(self._shape)

    # 5.shape getter and setter
    @property
    def shape(self):
        return self._shape

    @shape.setter
    def shape(self, shape):
        assert isinstance(shape, tuple), \
            f&#39;Input shape expects a tuple, but got {type(shape)}&#39;

        if len(shape) &lt;= 0 or shape[0] == 0:
            raise ValueError(
                &#39;Input shape is empty or format is invalid in calling function shape&#39;)

        self._shape = shape

    # 6.dtype getter and setter
    @property
    def dtype(self):
        return self._dtype

    @dtype.setter
    def dtype(self, dtype):
        try:
            self._dtype = np.dtype(dtype)
        except:
            raise TypeError(
                f&#39;Input dtype expects a numpy.dtype, but got {type(dtype)}&#39;)

    # 7.nbytes getter
    @property
    def nbytes(self):
        return self._nbytes

    # 8.itemsize getter
    @property
    def itemsize(self):
        return self._dtype.itemsize

    # 9.data format
    @property
    def format(self):
        return self._format

    @format.setter
    def format(self, format):
        if not isinstance(format, (str, int)):
            raise TypeError(
                f&#34;Input format expects int or string, but got {type(format)}.&#34;)

        self._format = format

    @property
    def size(self):
        return np.prod(self._shape)

    def reshape(self, shape):
        &#34;&#34;&#34;Gives a new shape to an array without changing its data.

        .. Note::
            Only modify the view of AscendArray.
            
        Args:
            shape (tuple[int]): Input new shape to be reshaped. It should be compatible with 
                the original shape.

        Returns:
            [AscendArray] : The original object with new shape.
        
        Typical usage example:
        ```python
        array = np.random.random(36*64).astype(&#39;float32&#39;).reshape(36, 64)
        ascend_array = ascend.AscendArray.clone(array)
        ascend_array = ascend_array.reshape(64, 36)
        ```
        &#34;&#34;&#34;
        assert isinstance(shape, tuple), \
            f&#39;Input shape expects tuple type, but got {type(shape)}.&#39;

        assert np.prod(self._shape) == np.prod(shape), \
            f&#34;The given shape({shape})&#39;s elements should same to {self._shape}.&#34;

        self._shape = shape
        return self

    def resize(self, shape: tuple):
        &#34;&#34;&#34;Resize the shape and data of AscendArray.

        .. Note::
            The data arrangement of AscendArray is modified.

        Args:
            shape (tuple): The resized new shape.

        Returns:
            [AscendArray] : The new object with a new shape.
        &#34;&#34;&#34;
        assert isinstance(shape, tuple), \
            f&#39;Input args of func reshape expects tuple type, but got {type(shape)}.&#39;

        pass

    def to_numpy(self, nbytes=None):
        &#34;&#34;&#34;Copy the attributes and data of AscendArray to np.ndarry object.

        Args:
            nbytes (int, optional): The data size of this object to be transformed. Defaults to None.

        Returns:
            [ndarray]: A copyed np.ndarray object

        Typical usage example:
        ```python
        array = np.random.random(3264)
        ascend_array = ascend.AscendArray.clone(array)
        data = ascend_array.to_numpy()
        ```
        &#34;&#34;&#34;
        if self._data is None:
            raise ValueError(&#39;Variable self._data is None in calling function to_np, \
                maybe this AscendArray instance parameter is null.&#39;)

        if nbytes and nbytes &gt; self._nbytes:
            raise ValueError(
                f&#34;Input nbytes must lower than {self._nbytes}, but got {nbytes}.&#34;)

        if self._flag != &#39;HOST&#39;:
            _nbytes = nbytes if nbytes else self._nbytes

            # copy device data to host
            cloned_array = AscendArray(shape=self._shape, dtype=self._dtype, format=self._format,
                                       context=self._context, flag=&#39;HOST&#39;)
            memcpy_d2h(cloned_array.ascend_data, self._data, _nbytes)
            numpy_ptr = cloned_array.ascend_data
        else:
            numpy_ptr = self._data

        try:
            np_type = const.numpy_dict[self._dtype]
        except KeyError:
            raise ValueError(
                f&#34;Convert AscendArray data to numpy not support this type {self._dtype}.&#34;)

        array = acl.util.ptr_to_numpy(numpy_ptr, self._shape, np_type)

        return array.copy()

    @property
    def to_np(self):
        return self.to_numpy()

    def to_ascend(self, array):
        &#34;&#34;&#34;Copy all the data of array(np.ndarray) to AscendArray.

        Args:
            array (np.ndarray): Input np.ndarray to be copyed.

        Typical usage example:
        ```python
        array = np.ones(shape=(384, 384), dtype=&#39;float16&#39;)
        ascend_array = AscendArray(shape=(384, 384), nbytes=array.nbytes, dtype=NPY_USHORT)
        ascend_array.to_ascend(array)
        ```
        &#34;&#34;&#34;
        if self._data is None:
            raise ValueError(&#39;instance arg self._data is None in calling function to_ascend, \
                Maybe this AscendArray instance parameter is null.&#39;)

        if self._flag == &#39;HOST&#39;:
            raise ValueError(
                f&#39;Method to_ascend only be used with DEVICE or DVPP memory&#39;)

        assert isinstance(array, np.ndarray), \
            f&#39;Function to_ascend args of input expects a np.ndarray object, but got {type(array)}&#39;

        assert (array.shape == self._shape) and (array.nbytes == self._nbytes), \
            &#39;Function to_ascend of input expects same shape and nbytes,&#39; \
            f&#39; but actually we got shape:{array.shape}, nbytes:{array.nbytes}.&#39;

        # get the array pointer for copy data to device
        array_ptr = acl.util.numpy_to_ptr(array)

        # do copy
        memcpy_h2d(self._data, array_ptr, self._nbytes)

    def astype(self, dtype):
        &#34;&#34;&#34; Cast a tensor from src data type to dst data type. Firstly, we try to use Cast operator 
            to release this function. If it fails, we use numpy astype method. 
        Args:
            dtype (np.dtype): The data type to be transformed.

        Returns:
            [AscendArray]: The new AscendArray data object.

        Typical usage example:
        ```python
        array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
        ascend_array = ascend.AscendArray.clone(array)
        ascend_array = ascend_array.astype(np.float16)
        ```
        &#34;&#34;&#34;
        try:
            from ..ops.op import Cast
            return Cast(self, dtype=dtype, context=self.context).data
        except:
            array = self.to_np.astype(dtype)
            return self.clone(array)

    def transpose(self, axes=None):
        &#34;&#34;&#34;Reverse or permute the axes of an array, and returns the modified array.

        Args:
            axes ([tuple, list], optional): Permute the axes of array. Defaults to None.

        Returns:
            [AscendArray]: A tranposed AscendArray.

        Typical usage example:
        ```python
        array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
        ascend_array = ascend.AscendArray.clone(array)
        ascend_array = ascend_array.astype(np.float16)
        ```
        &#34;&#34;&#34;
        if not isinstance(axes, (tuple, list)):
            raise TypeError(
                f&#34;Input axis expects a tuple or list, but got {type(axes)}.&#34;)

        try:
            from ..ops.op import Permute
            return Permute(self, axes=axes).data
        except:
            return np.transpose(self.to_np, axes=axes)

    @classmethod
    def clone(cls, array, context=None, format=None, flag=&#34;DEVICE&#34;):
        &#34;&#34;&#34;New an AscendArray object and clone all the attributes of array(np.ndarray) to it.

        Args:
            array (np.ndarray): A np.ndarray data to be cloned
            context (int, optional): The context resource working on. Defaults to None.
            format (data_format, optional): The cloned AscendArray data format, it should be &#39;NCHW&#39; 
                or &#39;NHWC&#39; for tensor, or it will be Ascend image format. Defaults to None.
            flag (str, optional): The Ascendarray memory flag, and it same to Ascend.Memory class. 
                Defaults to &#34;DEVICE&#34;.

        Raises:
            TypeError: The input array is not the intance of np.ndarray

        Returns:
            [AscendArray]: A cloned AscendArray object.

        Typical usage example:
        ```python
        array = np.random.random(644)
        data = ascend.AscendArray.clone(array)
        ```
        &#34;&#34;&#34;        
        assert isinstance(array, np.ndarray), \
            f&#39;Input args array expects class np.ndarray object, but got {type(array)}.&#39;

        if context and not isinstance(context, int):
            raise TypeError(
                f&#34;Input context expects int type, but got {type(context)}.&#34;)

        bind_context(context)

        # get the array pointer for copy device data to host
        array_ptr = acl.util.numpy_to_ptr(array)

        # new an AscendArray object shape like input array.
        cloned_array = cls(shape=array.shape, dtype=array.dtype,
                           format=format, context=context, flag=flag)

        # do copy
        memcpy_h2d(cloned_array.ascend_data, array_ptr, array.nbytes)

        return cloned_array

    def to(self, ascendarray):
        &#34;&#34;&#34;Copy this AscendArray data to another ascendarray(AscendArray).

        Args:
            ascendarray (AscendArray): The dst AscendArray to be assigned

        Typical usage example:
        ```python
        array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
        ascend_array1 = ascend.AscendArray.clone(array)
        ascend_array2 = ascend.AscendArray((128, 32), dtype=np.float32)
        ascend_array1.to(ascend_array2)
        ```
        &#34;&#34;&#34;
        if self._data is None:
            raise ValueError(&#34;Variable self._data is None in calling function &#39;to&#39;, \
                Maybe this AscendArray instance parameter is null.&#34;)

        assert isinstance(ascendarray, AscendArray), \
            f&#34;Input args of func &#39;to&#39; expects a class of AscendArray, but got {type(array)}.&#34;

        assert (self._nbytes &lt;= ascendarray.nbytes) and (self._dtype == ascendarray.dtype), \
            &#34;Shape or dtype of the input AscendArray is different from original.&#34;

        memcpy_d2d(ascendarray.ascend_data, self._data, self._nbytes)

    def __len__(self):
        &#34;&#34;&#34; Number of elements in the array, same to self.size.
        Args:
            None

        Returns:
            number of elements
        &#34;&#34;&#34;
        return np.prod(self._shape)

    def __getitem__(self, idx):
        &#34;&#34;&#34; get AscendArray data using subscript index
        Args:
            idx : an int or slice object

        Returns:
            data of AscendArray
        &#34;&#34;&#34;
        if self.dtype not in [
            np.dtype(&#39;float32&#39;),
            np.dtype(&#39;int8&#39;),
            np.dtype(&#39;int32&#39;),
            np.dtype(&#39;uint8&#39;)
        ]:
            raise TypeError(&#34;Only dtype in [&#39;float32&#39;, &#39;int32&#39;, &#39;int8&#39;, &#39;uint8&#39;] are support \
                            to using subscript index.&#34;)

        if not hasattr(self, &#39;_cloned_array&#39;):
            self._cloned_array = self.to_np
            self._cloned_array.reshape(self._shape)

        if isinstance(idx, int):
            if idx &lt; self.size and idx &gt;= 0:
                return self._cloned_array[idx]
            elif idx &gt; -self.size and idx &lt; 0:
                return self._cloned_array[idx + self.size]
            else:
                raise IndexError(f&#34;index {idx} is out of bounds for axis 0&#34;)

        elif isinstance(idx, slice):
            return self._cloned_array[idx]
        else:
            return &#39;index error&#39;

    def __setitem__(self, index, value):
        &#34;&#34;&#34; release to set AscendArray data using subscript index
        Args:
            idx : an int or slice object

        Returns:
            data of AscendArray
        &#34;&#34;&#34;
        import pdb
        pdb.set_trace()
        if not hasattr(self, &#39;_cloned_array&#39;):
            self._cloned_array = self.to_np

        if isinstance(index, int) and index &lt; self.size:
            self._cloned_array[index] = value
        elif isinstance(index, (list, tuple)):
            for i in index:
                assert i &lt; self.size, f&#39;index out of range.&#39;
            if isinstance(value, (list, tuple)):
                if len(index) == len(value):
                    for i, v in enumerate(index):
                        self._cloned_array[v] = value[i]
                else:
                    raise Exception(
                        &#39;values and index must be of the same length&#39;)
            elif isinstance(value, (int, float, str)):
                for i in index:
                    self._cloned_array[i] = value
            else:
                raise Exception(&#39;value error&#39;)
        else:
            raise Exception(&#39;index error&#39;)

        # update to device, it has lower performance for always write
        self.to_ascend(self._cloned_array)

    def __repr__(self):
        &#34;&#34;&#34; release to represent AscendArray data
        Args:
            None

        Returns:
            repr
        &#34;&#34;&#34;
        repr = &#34;ascendarray(\n{0}, dtype={1})&#34;.format(self.to_np, self.dtype)
        return repr

    def __del__(self):
        if hasattr(self, &#39;_mem&#39;):
            del self._mem
            self._data = None
        elif hasattr(self, &#39;_data&#39;) and self._data is not None:
            free(self._data, flag=self._flag)</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="ascend.data.AscendArray.clone"><code class="name flex">
<span>def <span class="ident">clone</span></span>(<span>array, context=None, format=None, flag='DEVICE')</span>
</code></dt>
<dd>
<div class="desc"><p>New an AscendArray object and clone all the attributes of array(np.ndarray) to it.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>array</code></strong> :&ensp;<code>np.ndarray</code></dt>
<dd>A np.ndarray data to be cloned</dd>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>The context resource working on. Defaults to None.</dd>
<dt><strong><code>format</code></strong> :&ensp;<code>data_format</code>, optional</dt>
<dd>The cloned AscendArray data format, it should be 'NCHW'
or 'NHWC' for tensor, or it will be Ascend image format. Defaults to None.</dd>
<dt><strong><code>flag</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The Ascendarray memory flag, and it same to Ascend.Memory class.
Defaults to "DEVICE".</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>TypeError</code></dt>
<dd>The input array is not the intance of np.ndarray</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a>]</code></dt>
<dd>A cloned AscendArray object.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(644)
data = ascend.AscendArray.clone(array)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L400-L443" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@classmethod
def clone(cls, array, context=None, format=None, flag=&#34;DEVICE&#34;):
    &#34;&#34;&#34;New an AscendArray object and clone all the attributes of array(np.ndarray) to it.

    Args:
        array (np.ndarray): A np.ndarray data to be cloned
        context (int, optional): The context resource working on. Defaults to None.
        format (data_format, optional): The cloned AscendArray data format, it should be &#39;NCHW&#39; 
            or &#39;NHWC&#39; for tensor, or it will be Ascend image format. Defaults to None.
        flag (str, optional): The Ascendarray memory flag, and it same to Ascend.Memory class. 
            Defaults to &#34;DEVICE&#34;.

    Raises:
        TypeError: The input array is not the intance of np.ndarray

    Returns:
        [AscendArray]: A cloned AscendArray object.

    Typical usage example:
    ```python
    array = np.random.random(644)
    data = ascend.AscendArray.clone(array)
    ```
    &#34;&#34;&#34;        
    assert isinstance(array, np.ndarray), \
        f&#39;Input args array expects class np.ndarray object, but got {type(array)}.&#39;

    if context and not isinstance(context, int):
        raise TypeError(
            f&#34;Input context expects int type, but got {type(context)}.&#34;)

    bind_context(context)

    # get the array pointer for copy device data to host
    array_ptr = acl.util.numpy_to_ptr(array)

    # new an AscendArray object shape like input array.
    cloned_array = cls(shape=array.shape, dtype=array.dtype,
                       format=format, context=context, flag=flag)

    # do copy
    memcpy_h2d(cloned_array.ascend_data, array_ptr, array.nbytes)

    return cloned_array</code></pre>
</details>
</dd>
</dl>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.data.AscendArray.ascend_data"><code class="name">var <span class="ident">ascend_data</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L112-L114" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def ascend_data(self): 
    return self._data</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.context"><code class="name">var <span class="ident">context</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L131-L133" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def context(self):
    return self._context</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.dtype"><code class="name">var <span class="ident">dtype</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L183-L185" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def dtype(self):
    return self._dtype</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.flag"><code class="name">var <span class="ident">flag</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L126-L128" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def flag(self):
    return self._flag</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.format"><code class="name">var <span class="ident">format</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L206-L208" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def format(self):
    return self._format</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.itemsize"><code class="name">var <span class="ident">itemsize</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L201-L203" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def itemsize(self):
    return self._dtype.itemsize</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.nbytes"><code class="name">var <span class="ident">nbytes</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L196-L198" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def nbytes(self):
    return self._nbytes</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.ndim"><code class="name">var <span class="ident">ndim</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L162-L164" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def ndim(self):
    return len(self._shape)</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.shape"><code class="name">var <span class="ident">shape</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L167-L169" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def shape(self):
    return self._shape</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.size"><code class="name">var <span class="ident">size</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L218-L220" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def size(self):
    return np.prod(self._shape)</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.to_np"><code class="name">var <span class="ident">to_np</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L313-L315" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def to_np(self):
    return self.to_numpy()</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.data.AscendArray.astype"><code class="name flex">
<span>def <span class="ident">astype</span></span>(<span>self, dtype)</span>
</code></dt>
<dd>
<div class="desc"><p>Cast a tensor from src data type to dst data type. Firstly, we try to use Cast operator
to release this function. If it fails, we use numpy astype method. </p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>dtype</code></strong> :&ensp;<code>np.dtype</code></dt>
<dd>The data type to be transformed.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a>]</code></dt>
<dd>The new AscendArray data object.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(64*64).astype('float32').reshape(64, 64)
ascend_array = ascend.AscendArray.clone(array)
ascend_array = ascend_array.astype(np.float16)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L351-L372" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def astype(self, dtype):
    &#34;&#34;&#34; Cast a tensor from src data type to dst data type. Firstly, we try to use Cast operator 
        to release this function. If it fails, we use numpy astype method. 
    Args:
        dtype (np.dtype): The data type to be transformed.

    Returns:
        [AscendArray]: The new AscendArray data object.

    Typical usage example:
    ```python
    array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
    ascend_array = ascend.AscendArray.clone(array)
    ascend_array = ascend_array.astype(np.float16)
    ```
    &#34;&#34;&#34;
    try:
        from ..ops.op import Cast
        return Cast(self, dtype=dtype, context=self.context).data
    except:
        array = self.to_np.astype(dtype)
        return self.clone(array)</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.reshape"><code class="name flex">
<span>def <span class="ident">reshape</span></span>(<span>self, shape)</span>
</code></dt>
<dd>
<div class="desc"><p>Gives a new shape to an array without changing its data.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Only modify the view of AscendArray.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple[int]</code></dt>
<dd>Input new shape to be reshaped. It should be compatible with
the original shape.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a>] </code></dt>
<dd>The original object with new shape.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(36*64).astype('float32').reshape(36, 64)
ascend_array = ascend.AscendArray.clone(array)
ascend_array = ascend_array.reshape(64, 36)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L222-L249" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def reshape(self, shape):
    &#34;&#34;&#34;Gives a new shape to an array without changing its data.

    .. Note::
        Only modify the view of AscendArray.
        
    Args:
        shape (tuple[int]): Input new shape to be reshaped. It should be compatible with 
            the original shape.

    Returns:
        [AscendArray] : The original object with new shape.
    
    Typical usage example:
    ```python
    array = np.random.random(36*64).astype(&#39;float32&#39;).reshape(36, 64)
    ascend_array = ascend.AscendArray.clone(array)
    ascend_array = ascend_array.reshape(64, 36)
    ```
    &#34;&#34;&#34;
    assert isinstance(shape, tuple), \
        f&#39;Input shape expects tuple type, but got {type(shape)}.&#39;

    assert np.prod(self._shape) == np.prod(shape), \
        f&#34;The given shape({shape})&#39;s elements should same to {self._shape}.&#34;

    self._shape = shape
    return self</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.resize"><code class="name flex">
<span>def <span class="ident">resize</span></span>(<span>self, shape: tuple)</span>
</code></dt>
<dd>
<div class="desc"><p>Resize the shape and data of AscendArray.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The data arrangement of AscendArray is modified.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple</code></dt>
<dd>The resized new shape.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a>] </code></dt>
<dd>The new object with a new shape.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L251-L266" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def resize(self, shape: tuple):
    &#34;&#34;&#34;Resize the shape and data of AscendArray.

    .. Note::
        The data arrangement of AscendArray is modified.

    Args:
        shape (tuple): The resized new shape.

    Returns:
        [AscendArray] : The new object with a new shape.
    &#34;&#34;&#34;
    assert isinstance(shape, tuple), \
        f&#39;Input args of func reshape expects tuple type, but got {type(shape)}.&#39;

    pass</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.to"><code class="name flex">
<span>def <span class="ident">to</span></span>(<span>self, ascendarray)</span>
</code></dt>
<dd>
<div class="desc"><p>Copy this AscendArray data to another ascendarray(AscendArray).</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>ascendarray</code></strong> :&ensp;<code><a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a></code></dt>
<dd>The dst AscendArray to be assigned</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(64*64).astype('float32').reshape(64, 64)
ascend_array1 = ascend.AscendArray.clone(array)
ascend_array2 = ascend.AscendArray((128, 32), dtype=np.float32)
ascend_array1.to(ascend_array2)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L445-L469" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def to(self, ascendarray):
    &#34;&#34;&#34;Copy this AscendArray data to another ascendarray(AscendArray).

    Args:
        ascendarray (AscendArray): The dst AscendArray to be assigned

    Typical usage example:
    ```python
    array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
    ascend_array1 = ascend.AscendArray.clone(array)
    ascend_array2 = ascend.AscendArray((128, 32), dtype=np.float32)
    ascend_array1.to(ascend_array2)
    ```
    &#34;&#34;&#34;
    if self._data is None:
        raise ValueError(&#34;Variable self._data is None in calling function &#39;to&#39;, \
            Maybe this AscendArray instance parameter is null.&#34;)

    assert isinstance(ascendarray, AscendArray), \
        f&#34;Input args of func &#39;to&#39; expects a class of AscendArray, but got {type(array)}.&#34;

    assert (self._nbytes &lt;= ascendarray.nbytes) and (self._dtype == ascendarray.dtype), \
        &#34;Shape or dtype of the input AscendArray is different from original.&#34;

    memcpy_d2d(ascendarray.ascend_data, self._data, self._nbytes)</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.to_ascend"><code class="name flex">
<span>def <span class="ident">to_ascend</span></span>(<span>self, array)</span>
</code></dt>
<dd>
<div class="desc"><p>Copy all the data of array(np.ndarray) to AscendArray.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>array</code></strong> :&ensp;<code>np.ndarray</code></dt>
<dd>Input np.ndarray to be copyed.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.ones(shape=(384, 384), dtype='float16')
ascend_array = AscendArray(shape=(384, 384), nbytes=array.nbytes, dtype=NPY_USHORT)
ascend_array.to_ascend(array)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L317-L349" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def to_ascend(self, array):
    &#34;&#34;&#34;Copy all the data of array(np.ndarray) to AscendArray.

    Args:
        array (np.ndarray): Input np.ndarray to be copyed.

    Typical usage example:
    ```python
    array = np.ones(shape=(384, 384), dtype=&#39;float16&#39;)
    ascend_array = AscendArray(shape=(384, 384), nbytes=array.nbytes, dtype=NPY_USHORT)
    ascend_array.to_ascend(array)
    ```
    &#34;&#34;&#34;
    if self._data is None:
        raise ValueError(&#39;instance arg self._data is None in calling function to_ascend, \
            Maybe this AscendArray instance parameter is null.&#39;)

    if self._flag == &#39;HOST&#39;:
        raise ValueError(
            f&#39;Method to_ascend only be used with DEVICE or DVPP memory&#39;)

    assert isinstance(array, np.ndarray), \
        f&#39;Function to_ascend args of input expects a np.ndarray object, but got {type(array)}&#39;

    assert (array.shape == self._shape) and (array.nbytes == self._nbytes), \
        &#39;Function to_ascend of input expects same shape and nbytes,&#39; \
        f&#39; but actually we got shape:{array.shape}, nbytes:{array.nbytes}.&#39;

    # get the array pointer for copy data to device
    array_ptr = acl.util.numpy_to_ptr(array)

    # do copy
    memcpy_h2d(self._data, array_ptr, self._nbytes)</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.to_numpy"><code class="name flex">
<span>def <span class="ident">to_numpy</span></span>(<span>self, nbytes=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Copy the attributes and data of AscendArray to np.ndarry object.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>nbytes</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>The data size of this object to be transformed. Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[ndarray]</code></dt>
<dd>A copyed np.ndarray object</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(3264)
ascend_array = ascend.AscendArray.clone(array)
data = ascend_array.to_numpy()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L268-L311" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def to_numpy(self, nbytes=None):
    &#34;&#34;&#34;Copy the attributes and data of AscendArray to np.ndarry object.

    Args:
        nbytes (int, optional): The data size of this object to be transformed. Defaults to None.

    Returns:
        [ndarray]: A copyed np.ndarray object

    Typical usage example:
    ```python
    array = np.random.random(3264)
    ascend_array = ascend.AscendArray.clone(array)
    data = ascend_array.to_numpy()
    ```
    &#34;&#34;&#34;
    if self._data is None:
        raise ValueError(&#39;Variable self._data is None in calling function to_np, \
            maybe this AscendArray instance parameter is null.&#39;)

    if nbytes and nbytes &gt; self._nbytes:
        raise ValueError(
            f&#34;Input nbytes must lower than {self._nbytes}, but got {nbytes}.&#34;)

    if self._flag != &#39;HOST&#39;:
        _nbytes = nbytes if nbytes else self._nbytes

        # copy device data to host
        cloned_array = AscendArray(shape=self._shape, dtype=self._dtype, format=self._format,
                                   context=self._context, flag=&#39;HOST&#39;)
        memcpy_d2h(cloned_array.ascend_data, self._data, _nbytes)
        numpy_ptr = cloned_array.ascend_data
    else:
        numpy_ptr = self._data

    try:
        np_type = const.numpy_dict[self._dtype]
    except KeyError:
        raise ValueError(
            f&#34;Convert AscendArray data to numpy not support this type {self._dtype}.&#34;)

    array = acl.util.ptr_to_numpy(numpy_ptr, self._shape, np_type)

    return array.copy()</code></pre>
</details>
</dd>
<dt id="ascend.data.AscendArray.transpose"><code class="name flex">
<span>def <span class="ident">transpose</span></span>(<span>self, axes=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Reverse or permute the axes of an array, and returns the modified array.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>axes</code></strong> :&ensp;<code>[tuple, list]</code>, optional</dt>
<dd>Permute the axes of array. Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a>]</code></dt>
<dd>A tranposed AscendArray.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(64*64).astype('float32').reshape(64, 64)
ascend_array = ascend.AscendArray.clone(array)
ascend_array = ascend_array.astype(np.float16)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L374-L398" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def transpose(self, axes=None):
    &#34;&#34;&#34;Reverse or permute the axes of an array, and returns the modified array.

    Args:
        axes ([tuple, list], optional): Permute the axes of array. Defaults to None.

    Returns:
        [AscendArray]: A tranposed AscendArray.

    Typical usage example:
    ```python
    array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
    ascend_array = ascend.AscendArray.clone(array)
    ascend_array = ascend_array.astype(np.float16)
    ```
    &#34;&#34;&#34;
    if not isinstance(axes, (tuple, list)):
        raise TypeError(
            f&#34;Input axis expects a tuple or list, but got {type(axes)}.&#34;)

    try:
        from ..ops.op import Permute
        return Permute(self, axes=axes).data
    except:
        return np.transpose(self.to_np, axes=axes)</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<header>
<a class="homelink" rel="home" title="ascendfly Home" href="https://gitee.com/ascend-fae/ascendfly">
<img src="https://bazige.github.io/ascend/logo/logo.png" alt=""> ascendfly
</a>
</header>
<div class="gcse-search" style="height: 70px"
data-as_oq="site:bazige.github.io inurl:github.com/ascendfly"
data-gaCategoryParameter="ascend.data">
</div>
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="ascend" href="../index.html">ascend</a></code></li>
</ul>
</li>
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="ascend.data.ascendarray" href="ascendarray.html">ascend.data.ascendarray</a></code></li>
<li><code><a title="ascend.data.tensor" href="tensor.html">ascend.data.tensor</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="ascend.data.imgs2tensor" href="#ascend.data.imgs2tensor">imgs2tensor</a></code></li>
<li><code><a title="ascend.data.tensor2imgs" href="#ascend.data.tensor2imgs">tensor2imgs</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="ascend.data.AscendArray" href="#ascend.data.AscendArray">AscendArray</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.data.AscendArray.ascend_data" href="#ascend.data.AscendArray.ascend_data">ascend_data</a></code></li>
<li><code><a title="ascend.data.AscendArray.astype" href="#ascend.data.AscendArray.astype">astype</a></code></li>
<li><code><a title="ascend.data.AscendArray.clone" href="#ascend.data.AscendArray.clone">clone</a></code></li>
<li><code><a title="ascend.data.AscendArray.context" href="#ascend.data.AscendArray.context">context</a></code></li>
<li><code><a title="ascend.data.AscendArray.dtype" href="#ascend.data.AscendArray.dtype">dtype</a></code></li>
<li><code><a title="ascend.data.AscendArray.flag" href="#ascend.data.AscendArray.flag">flag</a></code></li>
<li><code><a title="ascend.data.AscendArray.format" href="#ascend.data.AscendArray.format">format</a></code></li>
<li><code><a title="ascend.data.AscendArray.itemsize" href="#ascend.data.AscendArray.itemsize">itemsize</a></code></li>
<li><code><a title="ascend.data.AscendArray.nbytes" href="#ascend.data.AscendArray.nbytes">nbytes</a></code></li>
<li><code><a title="ascend.data.AscendArray.ndim" href="#ascend.data.AscendArray.ndim">ndim</a></code></li>
<li><code><a title="ascend.data.AscendArray.reshape" href="#ascend.data.AscendArray.reshape">reshape</a></code></li>
<li><code><a title="ascend.data.AscendArray.resize" href="#ascend.data.AscendArray.resize">resize</a></code></li>
<li><code><a title="ascend.data.AscendArray.shape" href="#ascend.data.AscendArray.shape">shape</a></code></li>
<li><code><a title="ascend.data.AscendArray.size" href="#ascend.data.AscendArray.size">size</a></code></li>
<li><code><a title="ascend.data.AscendArray.to" href="#ascend.data.AscendArray.to">to</a></code></li>
<li><code><a title="ascend.data.AscendArray.to_ascend" href="#ascend.data.AscendArray.to_ascend">to_ascend</a></code></li>
<li><code><a title="ascend.data.AscendArray.to_np" href="#ascend.data.AscendArray.to_np">to_np</a></code></li>
<li><code><a title="ascend.data.AscendArray.to_numpy" href="#ascend.data.AscendArray.to_numpy">to_numpy</a></code></li>
<li><code><a title="ascend.data.AscendArray.transpose" href="#ascend.data.AscendArray.transpose">transpose</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p><span style="color:#ddd">&#21328;</span></p>
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.9.2</a>.</p>
</footer>
</body>
</html>